package com.diycode.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.lang.reflect.Field;

/**
 * @author diycode
 * @date 2024-03-07
 */
public class QueryWrapperUtil<T> {
    /**
     * 将查询对象转换成MyBatisPlus中的QueryWrapper
     *
     * @param query
     * @param <T>
     * @return
     */
    public static <T> QueryWrapper<T> build(Object query) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();

        //获取Query类中都有哪些属性
        final Field[] fields = query.getClass().getDeclaredFields();
        for (Field field : fields) {
            //设置field的私有方法可以访问
            field.setAccessible(true);
            //对象query中该field的值
            Object fieldValue = null;
            try {
                //获取对象指定属性的值
                fieldValue = field.get(query);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (fieldValue != null) {
                //获取Query类属性的名称
                final String fieldName = field.getName();

                //跳过serialVersionUID
                if (fieldName.equals("serialVersionUID")) {
                    continue;
                }
                //获取Query类对应的表字段名
                final String columnName = camelToUnderline(fieldName);

                String type = field.getGenericType().toString();
                switch (type) {
                    case "class java.lang.String":
                        queryWrapper.like(columnName, fieldValue);
                        break;
                    case "class java.lang.Integer":
                    case "class java.lang.Long":
                    case "class java.lang.Short":
                    case "class java.lang.Boolean":
                        queryWrapper.eq(columnName, fieldValue);
                        break;
                }
            }
        }
        return queryWrapper;
    }

    /**
     * 添加or关系
     *
     * @param logic
     * @param queryWrapper
     * @param <T>
     */
    private static <T> void fun(String logic, QueryWrapper<T> queryWrapper) {
        if ("or".equalsIgnoreCase(logic)) {
            queryWrapper.or();
        }
    }

    /**
     * 将驼峰命名转化成下划线
     *
     * @param para
     * @return
     */
    public static String camelToUnderline(String para) {
        StringBuilder sb = new StringBuilder(para);
        // 定位
        int temp = 0;
        // 从第2个字符开始 避免命名不规范
        for (int i = 1; i < para.length(); i++) {
            if (Character.isUpperCase(para.charAt(i))) {
                sb.insert(i + temp, "_");
                temp += 1;
            }
        }
        return sb.toString().toLowerCase();
    }
}
